package com.erclab.internal.xpresso.formelements;

import java.util.Properties;

import com.erclab.internal.xpresso.forms.Form;

public class HTMLArea extends SimpleTextArea {

	
	public String toHTML(Form theForm) {
		Properties props = this.getElementParameters();
		String cols = props.getProperty("htmlarea.cols");
		String rows = props.getProperty("htmlarea.rows");
		String editorUrl = props.getProperty("htmlarea.editor.url");
		String editorConfUrl = props.getProperty("htmlarea.editor.conf.url");
		
		StringBuffer sb = new StringBuffer();
		
		sb.append("<script type=\"text/javascript\">");
		sb.append("_editor_url = \"" + editorUrl + "\";");
		sb.append("_editor_lang = \"en\";");
		sb.append("</script>");
				
		sb.append("<TEXTAREA name=\"Field");
		sb.append(idFormElement + "\" ");
		sb.append("id=\"Field");
		sb.append(idFormElement + "\" ");
		
		if (cols != null){
			sb.append("cols=\"" + cols + "\" ");
		}
		if (rows != null){
			sb.append("rows=\"" + rows + "\" ");
		}
		sb.append("class=\"" + this.style + "TextArea\">");
		//sb.append(">");
		if (theForm.getFormParameters().getAction().equals("update")){
			if(originalValue != null){
				sb.append(originalValue);
			}
		} else {
			if(lookupValue != null){
				sb.append(this.lookupValue);
			}
		}
		sb.append(" </TEXTAREA>");
		
		sb.append("<script type=\"text/javascript\" src=\"" + editorConfUrl + "\"></script>" +
				"<script type=\"text/javascript\">" +
				"var editor = null;" +
				"function initHtmlArea(){" +
				"editor = new HTMLArea(\"Field" + this.idFormElement + "\");" + 
				"editor.generate();}" +
				"</script>" +
				"<img src=\"../xpresso/html/images/Spacer.gif\" onLoad=\"setTimeout('initHtmlArea()', 1000);\">");		
		
		return sb.toString();
	}

	@Override
	public String[] processSubmittedValues(Form theForm, String[] submittedValues) {
		String submitted = submittedValues[0];
		if (submittedValues != null){
			// Remove trailing <p> and </p>
			if (submitted.startsWith("<p>") && submitted.endsWith("</p>")){
				submitted = submitted.substring(3,submitted.length()-4);
				return new String[]{submitted};
			}
		}
		return submittedValues;
	}
	
		
	
}
